package org.example;

import org.junit.Test;

import java.util.Objects;
import java.util.concurrent.*;

public class DemoTest5 {
    @Test
    public void testCompletableWhenComplete() throws ExecutionException, InterruptedException {
        CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> {

            if (Math.random() < 0.5) {
                throw new RuntimeException("出错了");
            }
            System.out.println("正常结束");
            return 0.11;

        }).whenComplete((aDouble, throwable) -> {
            if (aDouble == null) {
                System.out.println("whenComplete  aDouble  is  null");
            } else {
                System.out.println("whenComplete  aDouble  is  " + aDouble);
            }
            if (throwable == null) {
                System.out.println("whenComplete  throwable  is  null");
            } else {
                System.out.println("whenComplete  throwable  is  " + throwable.getMessage());
            }
        });
        System.out.println("最终返回的结果  =  " + future.get());
    }


    @Test
    public void testWhenCompleteExceptionally() throws ExecutionException, InterruptedException {
        CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> {
            if (Math.random() < 0.5) {
                throw new RuntimeException("出错了");
            }
            System.out.println("正常结束");
            return 0.11;

        }).whenComplete((aDouble, throwable) -> {
            if (aDouble == null) {
                System.out.println("whenComplete  aDouble  is  null");
            } else {
                System.out.println("whenComplete  aDouble  is  " + aDouble);
            }
            if (throwable == null) {
                System.out.println("whenComplete  throwable  is  null");
            } else {
                System.out.println("whenComplete  throwable  is  " + throwable.getMessage());
            }
        }).exceptionally(throwable -> {
            System.out.println("exceptionally中异常：" + throwable.getMessage());
            return 0.0;
        });

        System.out.println("最终返回的结果  =  " + future.get());
    }
}
